package com.github.postsanf.yinian.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.example.audiorecordmp3demo.utils.RecorderAndPlayUtil;
import com.example.lamemp3.MP3Recorder;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.MainFragmentAdapter;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.bean.YNImageFloder;
import com.github.postsanf.yinian.bean.YNTodayM;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNAlbumResponse;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.entity.YNGetUserResponse;
import com.github.postsanf.yinian.entity.YNTodayMResponse;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.fragment.HomeAlbumFragment;
import com.github.postsanf.yinian.fragment.MineFragement;
import com.github.postsanf.yinian.fragment.PeopleTimeLineFragment;
import com.github.postsanf.yinian.huanxin.Constant;
import com.github.postsanf.yinian.huanxin.DemoHelper;
import com.github.postsanf.yinian.huanxin.runtimepermissions.PermissionsManager;
import com.github.postsanf.yinian.huanxin.runtimepermissions.PermissionsResultAction;
import com.github.postsanf.yinian.mp3.StorageUtil;
import com.github.postsanf.yinian.myzxing.android.CaptureActivity;
import com.github.postsanf.yinian.service.AlbumService;
import com.github.postsanf.yinian.service.BackUpService;
import com.github.postsanf.yinian.service.DemoIntentService;
import com.github.postsanf.yinian.service.DemoPushService;
import com.github.postsanf.yinian.service.StatisticsService;
import com.github.postsanf.yinian.service.UpLoadService;
import com.github.postsanf.yinian.service.UpdateManager;
import com.github.postsanf.yinian.utils.Crop;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.DoSecretUtils;
import com.github.postsanf.yinian.utils.ImageUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.TimeUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.utils.YNInviteSecret;
import com.github.postsanf.yinian.widget.NoScrollViewPager;
import com.hyphenate.util.EMLog;
import com.igexin.sdk.PushManager;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import sweetcamera.CameraActivity;

/**
 * 忆年首页
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {
    public static Activity myMainActivity;
    private final int SCANER_CODE = 1;
    private List<Fragment> fragments = new ArrayList<>();
    public static int goodsid;
    private RelativeLayout rl_album_newuser;
    public boolean isConflict = false;
    private Map<String, Integer> map3 = new HashMap<>(); //埋点时间记录
    private Map<String, Integer> map4 = new HashMap<>(); //埋点时间记录
    private Map<String, Integer> map5 = new HashMap<>(); //埋点时间记录
    private Map<String, Integer> map6 = new HashMap<>(); //埋点时间记录
    private int num;
    private long time;
    private List<Integer> netType = new ArrayList<>();
    public static String micpath;
    public static boolean mp3IsExist;
    public static int timer = 0;
    public static String micUrl = "";
    public static String locationTx = "";
    private NotificationManager manager;
    private NoScrollViewPager mViewPager;
    private MainFragmentAdapter mViewPagerAdaper;
    private RelativeLayout tabiv1, tabiv3;
    private RelativeLayout ll_buttons, ll_buttons_ll;
    private ImageView buttons_cover;
    private LinearLayout buttons_cover_top;
    private ImageView select1, tabiv2, select3;
    private ImageView btn_middle_selector_copy;
    private TextView my_album_num;
    private TextView buttons_cover_day, buttons_cover_week, buttons_cover_yeanmoutn;
    private TextView selecttv1, selecttv3;
    private File mTempDir;
    private UploadManager mUpManager;
    private AnimationDrawable _animaition;
    private AnimationDrawable _animaition2;
    private RelativeLayout rl_timeline_guide;
    private ImageView anim_pailide_new;
    private AnimationDrawable anim_pailide_new_animaition;

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        if (outState != null) {
            String FRAGMENTS_TAG = "android:support:fragments";
            outState.remove(FRAGMENTS_TAG);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("xjs","mmmonStart===>");
        SharedPreferences sp = getSharedPreferences("OURINFO", MODE_PRIVATE);
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean("active", true);
        ed.commit();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("xjs","mmmonstop===>");

    }


    private void ExitYiNian() {
        SharedPreferences.Editor ed = application.getSp_login().edit();
        ed.putString(getString(R.string.SP_YNS_PASSWORD), DoSecretUtils.doSecretStr(""));
        ed.putString(getString(R.string.LID), DoSecretUtils.doSecretStr(""));
        ed.commit();
        application.clearAllData();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //make sure activity will not in background if user is logged into another device or removed
        if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) {
            DemoHelper.getInstance().logout(false, null);
            ExitYiNian();
            finish();
            startActivity(new Intent(this, LoginActivity.class));
            return;
        } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
            finish();
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        myMainActivity = MainActivity.this;
        setContentView(R.layout.activity_main);
        mUpManager = application.getUploadManager();
        time = System.currentTimeMillis();
        requestPermissions();
        registerBoradcastReceiver();
        application.addActivity(this);
        mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
        if (!(mTempDir.mkdir() || mTempDir.isDirectory())) {
            mTempDir.mkdirs();
        }
        PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.
                class);
        updateCID(true);
        initView();
        initContinueUpLoadService();
        initjudieAccountRemove();
        checkUpdataAPP();
        initStatistic();
        InitRecorder();
        initTimeMark();
        initUpload30Images();
        initLocation();
        initNoticeWeek();
        DownNewDay();
        SharedPreferences sp = getSharedPreferences("OURINFO", MODE_PRIVATE);
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean("active", true);
        ed.commit();
    }

    private void DownNewDay() {
        final String str = new SimpleDateFormat("yyyy-MM-dd").format(new Date(new Date().getTime()));
        String newday = SpUtils.getString(MainActivity.this, "DownNewDay");
        if (newday.equals(str))
            return;
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/h5/ShowTodayMemoryInThreeDay")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNTodayMResponse resToday = gson.fromJson(s, YNTodayMResponse.class);
                        if (resToday != null && ReqUtils.isSuccess(resToday.getCode())) {
                            List<YNTodayM> mDatas = resToday.getData();
                            if (mDatas.size() > 0) {
                                String tommorw = new SimpleDateFormat("yyyy-MM-dd").format(new Date(new Date().getTime() + 24 * 60 * 60 * 1000));
                                String tomorrowpic = mDatas.get(0).getTMpic();
                                SpUtils.put(MainActivity.this, "newTomorrowDate", tommorw);
                                SpUtils.put(MainActivity.this, "newTomorrowText", mDatas.get(0).getTMtext());
                                downPic(tomorrowpic, tommorw + ".jpg");
                                String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date(new Date().getTime()));
                                String todaypic = mDatas.get(1).getTMpic();
                                SpUtils.put(MainActivity.this, "newtodayDate", today);
                                SpUtils.put(MainActivity.this, "newtodayText", mDatas.get(1).getTMtext());
                                downPicToday(todaypic, today + ".jpg");
                                SpUtils.put(MainActivity.this, "DownNewDay", str);
                            }
                        } else {
                            showToast(resToday.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(getString(R.string.YN_NET_LINK));
                    }
                });
        liteHttp.executeAsync(req);
    }


    private void downPicToday(final String url, final String name) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), ".yiniantodayshow");
        if (!(file.mkdir() || file.isDirectory())) {
            file.mkdirs();
        }
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    URL url1 = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream is = conn.getInputStream();
                        String localPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.yiniantodayshow/" + name;
                        File f = new File(localPath);
                        if (f.exists()) {
                            f.delete();
                        }
                        FileOutputStream fos = new FileOutputStream(f);
                        int len = 0;
                        byte[] buff = new byte[1024];
                        while ((len = is.read(buff)) != -1) {
                            fos.write(buff, 0, len);
                        }
                        is.close();
                        fos.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void downPic(final String url, final String name) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), ".yiniantodayshow");
        if (file.exists()) {
            file.delete();
        }
        if (!(file.mkdir() || file.isDirectory())) {
            file.mkdirs();
        }
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    URL url1 = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream is = conn.getInputStream();
                        String localPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.yiniantodayshow/" + name;
                        File f = new File(localPath);
                        if (f.exists()) {
                            f.delete();
                        }
                        FileOutputStream fos = new FileOutputStream(f);
                        int len = 0;
                        byte[] buff = new byte[1024];
                        while ((len = is.read(buff)) != -1) {
                            fos.write(buff, 0, len);
                        }
                        is.close();
                        fos.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void initNoticeWeek() {
        int thisway = SpUtils.getInt(MainActivity.this, "way");
        Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        int mWay = c.get(Calendar.DAY_OF_WEEK);
        if (mWay != thisway) {
            boolean isKuoRongShow = SpUtils.getBoolean(MainActivity.this, "isKuoRongShow");
            if (isKuoRongShow) {
                startActivity(new Intent(MainActivity.this, EveryDayNoticeDialogActivity.class));
            }
        }
        SpUtils.put(this, "way", mWay);
    }

    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    public static String LocationCity = "";

    private void initLocation() {
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(mAMapLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setMockEnable(false);
        mLocationOption.setHttpTimeOut(20000);
        mLocationOption.setLocationCacheEnable(false);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    LocationCity = amapLocation.getCity();
                }
            }
        }
    };

    boolean btnAnimation = false;

    private void OpenButtons() {
        if (btnAnimation) {
            return;
        }
        btnAnimation = true;
        btn_middle_selector_copy.setVisibility(View.VISIBLE);
        RotateAnimation rotateAnimationtab = new RotateAnimation(0, -135f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        Animation translateAnimationtab = new TranslateAnimation(0, 0, UIHelper.dip2px(MainActivity.this, 5), 0);
        AnimationSet animationSettab = new AnimationSet(true);
        animationSettab.addAnimation(rotateAnimationtab);
        animationSettab.addAnimation(translateAnimationtab);
        animationSettab.setFillAfter(true);
        animationSettab.setDuration(500);
        animationSettab.setInterpolator(new DecelerateInterpolator());
        tabiv2.setVisibility(View.GONE);
        btn_middle_selector_copy.startAnimation(animationSettab);
        Animation translateAnimationbtns = new TranslateAnimation(0, 0, UIHelper.dip2px(MainActivity.this, 120), 0);
        AlphaAnimation alphaAnimationbtns = new AlphaAnimation(0.0f, 1.0f);
        AnimationSet animationSetbtns = new AnimationSet(true);
        animationSetbtns.addAnimation(translateAnimationbtns);
        animationSetbtns.addAnimation(alphaAnimationbtns);
        animationSetbtns.setDuration(500);
        ll_buttons_ll.startAnimation(animationSetbtns);
        ll_buttons.setVisibility(View.VISIBLE);
        Animation translateAnimationf = new TranslateAnimation(0, 0, -UIHelper.dip2px(MainActivity.this, 50), 0);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
        AnimationSet animationSet = new AnimationSet(true);
        animationSet.addAnimation(translateAnimationf);
        animationSet.addAnimation(alphaAnimation);
        animationSet.setDuration(800);
        buttons_cover_top.startAnimation(animationSet);
        buttons_cover_top.setVisibility(View.VISIBLE);
        AlphaAnimation alphaAnimationcover = new AlphaAnimation(0.0f, 1.0f);
        alphaAnimationcover.setDuration(800);
        buttons_cover.startAnimation(alphaAnimationcover);
        buttons_cover.setVisibility(View.VISIBLE);
    }

    private void CloseButtons() {
        if (!btnAnimation) {
            return;
        }
        btnAnimation = false;
//        RotateAnimation rotateAnimationtab = new RotateAnimation(-135f, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//        Animation translateAnimationtab = new TranslateAnimation(0, 0, 0, UIHelper.dip2px(MainActivity.this, 5));
//        translateAnimationtab.setFillAfter(true);
//        animationSettab = new AnimationSet(true);
//        animationSettab.addAnimation(rotateAnimationtab);
//        animationSettab.addAnimation(translateAnimationtab);
//        animationSettab.setFillAfter(true);
//        animationSettab.setDuration(500);
//        animationSettab.setInterpolator(new DecelerateInterpolator());
//        btn_middle_selector_copy.startAnimation(animationSettab);
        btn_middle_selector_copy.setVisibility(View.GONE);
//        animationSettab.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//            }
//
//            @Override
//            public void onAnimationEnd(Animation animation) {
//                tabiv2.setVisibility(View.VISIBLE);
//                btn_middle_selector_copy.setVisibility(View.GONE);
//            }
//
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//            }
//        });
        ll_buttons.setVisibility(View.GONE);
        tabiv2.setVisibility(View.VISIBLE);
        Animation translateAnimationbtns = new TranslateAnimation(0, 0, 0, UIHelper.dip2px(MainActivity.this, 120));
        AlphaAnimation alphaAnimationbtns = new AlphaAnimation(1.0f, 0.0f);
        AnimationSet animationSetbtns = new AnimationSet(true);
        animationSetbtns.addAnimation(translateAnimationbtns);
        animationSetbtns.addAnimation(alphaAnimationbtns);
        animationSetbtns.setDuration(500);
        ll_buttons_ll.startAnimation(animationSetbtns);

        Animation translateAnimationf = new TranslateAnimation(0, 0, 0, -UIHelper.dip2px(MainActivity.this, 50));
        AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
        AnimationSet animationSet = new AnimationSet(true);
        animationSet.addAnimation(translateAnimationf);
        animationSet.addAnimation(alphaAnimation);
        animationSet.setDuration(800);
        buttons_cover_top.startAnimation(animationSet);
        animationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                buttons_cover_top.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        AlphaAnimation alphaAnimationcover = new AlphaAnimation(1.0f, 0.0f);
        alphaAnimationcover.setDuration(800);
        buttons_cover.startAnimation(alphaAnimationcover);
        alphaAnimationcover.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                buttons_cover.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
//        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//            }
//            @Override
//            public void onAnimationEnd(Animation animation) {
//                sendBroadcast(new Intent(ACTIONs.spacebuttonsgone));
//            }
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//            }
//        });

//        sendBroadcast(new Intent(ACTIONs.spacetopsgone));
//        translateAnimationf.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//
//            }
//
//            @Override
//            public void onAnimationEnd(Animation animation) {
////                sendBroadcast(new Intent(ACTIONs.spacetopsgone));
//
//            }
//
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//
//            }
//        });
    }

    boolean gisswitch = false;
    private float mLastMotionX;
    boolean flag = false;


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastMotionX = ev.getX();
                mViewPager.setScrollble(true);
                if ((float) (UIHelper.getScreenWidth(MainActivity.this) - UIHelper.dip2px(MainActivity.this, 20)) < mLastMotionX && mLastMotionX < (float) UIHelper.getScreenWidth(MainActivity.this)) {
                    flag = true;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (flag) {
                    if (ev.getX() - mLastMotionX < -15 && mViewPager.getCurrentItem() == 1) {
                        flag = false;
                        mViewPager.setScrollble(false);
                        if (PeopleTimeLineFragment.buttonsCanClick)
                            sendBroadcast(new Intent("SlidingMenuOpen"));
                    }
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_space_selector:
                sendBroadcast(new Intent("SlidingMenuCanOpen").putExtra("canopen", false));
                mViewPager.setCurrentItem(0);
                gisswitch = true;
                break;
            case R.id.btn_middle_selector:
                if (mViewPager.getCurrentItem() != 1) {
                    mViewPager.setCurrentItem(1);
                    sendBroadcast(new Intent("SlidingMenuCanOpen").putExtra("canopen", true));
                } else {
                    if (PeopleTimeLineFragment.buttonsCanClick) {
                        OpenButtons();
                    } else {
                        Toast.makeText(this, "先创建圈子才能发布内容", Toast.LENGTH_SHORT).show();
                    }
                }
                gisswitch = false;
                rl_timeline_guide.setVisibility(View.GONE);
                SpUtils.put(MainActivity.this, "homeZhidaole", true);
                break;
            case R.id.buttons_cover:
            case R.id.btn_middle_selector_copy:
                CloseButtons();
                break;
            case R.id.btn_me_selector:
                sendBroadcast(new Intent("SlidingMenuCanOpen").putExtra("canopen", false));
                mViewPager.setCurrentItem(2);
                gisswitch = true;
                break;
            case R.id.tv_image:
                ImageLocalSelectActivity.IsSmall = false;
                startActivity(new Intent(MainActivity.this, ImageLocalSelectActivity.class).putExtra("mainImage", true));
                CloseButtons();
                break;
            case R.id.tv_video:
                ImageLocalSelectActivity.IsSmall = false;
                startActivity(new Intent(MainActivity.this, VideoLocalSelectActivity.class));
                CloseButtons();
                break;
            case R.id.tv_word:
                ImageLocalSelectActivity.IsSmall = false;
                startActivity(new Intent(MainActivity.this, TextEditActivity.class).putExtra("mainText", true));
                CloseButtons();
                break;
            case R.id.tv_location:
                ImageLocalSelectActivity.IsSmall = false;
                startActivity(new Intent(MainActivity.this, ImageLocationEditActivity.class).putExtra("mainLocation", true));
                CloseButtons();
                break;
            case R.id.tv_mic:
                ImageLocalSelectActivity.IsSmall = false;
                startActivity(new Intent(MainActivity.this, MicAddActivity.class).putExtra("mainMic", true));
                CloseButtons();
                break;
            case R.id.tv_pailide:
                ImageLocalSelectActivity.IsSmall = false;
                startActivity(new Intent(MainActivity.this, CameraActivity.class).putExtra("mainPailide", true));
                CloseButtons();
                break;

        }
    }

    private void initStatistic() {
        //将上次存储的数据上传服务器
        String json = SpUtils.getString(MainActivity.this, "json");
        if (json.startsWith("{")) {
            Intent intent = new Intent(MainActivity.this, StatisticsService.class);
            intent.setAction(ACTIONs.uploadRecode);
            intent.putExtra("json", json);
            startService(intent);
        }
    }

    Handler backuphandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DELETE_DIFFYUN:
                    if (msg.obj != null) {
                        String key = (String) msg.obj;
                        List<String> list = new ArrayList<>();
                        if (key.contains(",")) {
                            String[] picarrs = key.split(",");
                            for (int i = 0; i < picarrs.length; i++) {
                                list.add(picarrs[i]);
                            }
                            if (list.size() > 20) {
                                List<List<String>> result = UIHelper.createList(list, 4);
                                for (List<String> subArr : result) {
                                    String deletes = null;
                                    for (String dd : subArr) {
                                        if (deletes == null) {
                                            deletes = dd;
                                        } else {
                                            deletes = deletes + "," + dd;
                                        }
                                        if (deletes != null)
                                            deleteDiffImages(deletes);
                                    }
                                }
                            } else {
                                deleteDiffImages(key);
                            }
                        } else {
                            deleteDiffImages(key);
                        }
                    }
                    break;
                case UPLOAD_DIFFLOCAL:
                    if (msg.obj != null) {
                        String key = (String) msg.obj;
                        Intent mIntent = new Intent(MainActivity.this, BackUpService.class);
                        mIntent.setAction(ACTIONs.actionBackupPhoto);
                        mIntent.putExtra(ACTIONs.aUrl, key);
                        mIntent.putExtra(ACTIONs.aUserId, application.getCurID());
                        startService(mIntent);
                    }
                    break;
            }
        }
    };

    private void deleteDiffImages(String key) {
        String urlsto = getString(R.string.SLIVER_URL) + "DeleteUserPhoto";
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put("key", key);
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            Log.i("xjs", "deleteDiffImages+sss==>" + s);
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.optString("msg").equals("success")) {
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void initUpload30Images() {
        String urlsto = getString(R.string.SLIVER_URL) + "GetUserAllPhotoHash";
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            Log.i("xjs", "initUpload30Images+sss==>" + s);
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.optString("msg").equals("success")) {
                                JSONArray dataArray = jsonObject.optJSONArray("data");
                                if (dataArray.length() == 0) {
                                    getImages();
                                } else if (dataArray.length() > 0) {
                                    //同步（删除）操作
                                    List<String> keys = new ArrayList<String>();
                                    keys.clear();
                                    for (int i = 0; i < dataArray.length(); i++) {
                                        keys.add(dataArray.optJSONObject(i).optString("key"));
                                    }
                                    compareImages(keys);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private HashSet<String> mDirPaths = new HashSet<String>();
    private List<YNImageFloder> mImageFloders = new ArrayList<YNImageFloder>();
    private List<String> ynImageList = new ArrayList<>();

    private void getImages() {
        ynImageList.clear();
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;
                Cursor mCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png", "image/gif"},
                        MediaStore.Images.Media.DATE_MODIFIED);
                while (mCursor.moveToNext()) {
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    if (firstImage == null)
                        firstImage = path;
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    YNImageFloder imageFloder = null;
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        imageFloder = new YNImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }
                    if (imageFloder.getDir().contains("DCIM"))
                        mImageFloders.add(imageFloder);
                }
                mCursor.close();
                mDirPaths = null;
                for (int j = 0; j < mImageFloders.size(); j++) {
                    File[] files = new File(mImageFloders.get(j).getDir()).listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            String filename = file.getName().toLowerCase();
                            if (file.length() > 0 && !filename.contains(".9")) {
                                if (filename.endsWith(".jpg") || filename.endsWith(".png")
                                        || filename.endsWith(".jpeg") || filename.endsWith(".gif"))
                                    return true;
                            }
                            return false;
                        }
                    });
                    if (files != null) {
                        for (int k = 0; k < files.length; k++) {
//                            Log.i("xjs", "k.path===>" + files[k].getAbsolutePath());
                            ynImageList.add(files[k].getAbsolutePath());
                        }
                    }
                }
                List<String> uploadlist = new ArrayList<>();
                uploadlist.clear();
                ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
                if (networkInfo != null && networkInfo.isAvailable()) {
                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        //WiFi网络
                        Log.i("xjs", "wifi");
                        uploadlist.addAll(ynImageList);
                    } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        //3g网络
                        Log.i("xjs", "3g网络");
                        if (ynImageList.size() > 10) {
                            for (int m = 0; m < 10; m++) {
                                uploadlist.add(ynImageList.get(m));
                            }
                        } else {
                            uploadlist.addAll(ynImageList);
                        }
                    }
                }
                String uploadspath = null;
                for (String str : uploadlist) {
                    if (uploadspath == null) {
                        uploadspath = str;
                    } else {
                        uploadspath = uploadspath + "," + str;
                    }
                }
                if (uploadspath != null) {
                    Log.i("xjs", "uploads=" + uploadspath);
                    Message uploadmessage = new Message();
                    uploadmessage.obj = uploadspath;
                    uploadmessage.what = UPLOAD_DIFFLOCAL;
                    backuphandler.sendMessage(uploadmessage);
                }
            }
        }).start();
    }

    private final int DELETE_DIFFYUN = 2;
    private final int UPLOAD_DIFFLOCAL = 3;

    private void compareImages(final List<String> keys) {
        ynImageList.clear();
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;
                Cursor mCursor = application.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png", "image/gif"},
                        MediaStore.Images.Media.DATE_MODIFIED);
                while (mCursor.moveToNext()) {
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    if (firstImage == null)
                        firstImage = path;
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    YNImageFloder imageFloder = null;
                    // 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        imageFloder = new YNImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }
                    if (imageFloder.getDir().contains("DCIM"))
                        mImageFloders.add(imageFloder);
                }
                mCursor.close();
                mDirPaths = null;
                for (int j = 0; j < mImageFloders.size(); j++) {
                    File[] files = new File(mImageFloders.get(j).getDir()).listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            String filename = file.getName().toLowerCase();
                            if (file.length() > 0 && !filename.contains(".9")) {
                                if (filename.endsWith(".jpg") || filename.endsWith(".png")
                                        || filename.endsWith(".jpeg") || filename.endsWith(".gif"))
                                    return true;
                            }
                            return false;
                        }
                    });
                    if (files != null) {
                        for (int k = 0; k < files.length; k++) {
                            ynImageList.add(files[k].getAbsolutePath());
//                            Log.i("xjs", "k.path===>" + files[k].getAbsolutePath());
                        }
                    }
                }
//                Log.i("xjs", "ynImageList.ssss===>" + ynImageList.size());
                List<String> diffyun = new ArrayList<String>();
                diffyun.clear();
                for (String str : keys) {
                    if (!ynImageList.contains(str))
                        diffyun.add(str);
                }
                String deletes = null;
                for (String str : diffyun) {
                    if (deletes == null) {
                        deletes = str;
                    } else {
                        deletes = deletes + "," + str;
                    }
                }
                if (deletes != null) {
                    Log.i("xjs", "deletes=" + deletes);
                    Message delmessage = new Message();
                    delmessage.obj = deletes;
                    delmessage.what = DELETE_DIFFYUN;
                    backuphandler.sendMessage(delmessage);

                }
                List<String> difflocal = new ArrayList<String>();
                difflocal.clear();
                for (String str : ynImageList) {
                    if (!keys.contains(str))
                        difflocal.add(str);
                }
                List<String> uploadlist = new ArrayList<>();
                uploadlist.clear();
                ConnectivityManager connectivityManager = (ConnectivityManager)
                        getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                if (networkInfo != null && networkInfo.isAvailable()) {
                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        //WiFi网络
                        Log.i("xjs", "wifi");
                        uploadlist.addAll(difflocal);
                    } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        //3g网络
                        Log.i("xjs", "3g网络");
                        if (difflocal.size() > 10) {
                            for (int m = 0; m < 10; m++) {
                                uploadlist.add(difflocal.get(m));
                            }
                        } else {
                            uploadlist.addAll(difflocal);
                        }
                    }
                }
                Log.i("xjs", "uploadlist.ssss===>" + uploadlist.size());
                String uploads = null;
                for (String str : uploadlist) {
                    if (uploads == null) {
                        uploads = str;
                    } else {
                        uploads = uploads + "," + str;
                    }
                }
                if (uploads != null) {
                    Log.i("xjs", "uploads=" + uploads);
                    Message uploadmessage = new Message();
                    uploadmessage.obj = uploads;
                    uploadmessage.what = UPLOAD_DIFFLOCAL;
                    backuphandler.sendMessage(uploadmessage);
                }
            }
        }).start();
    }

    private void initTimeMark() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowUserTimeMark))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNAlbumResponse resGroup = gson.fromJson(s, YNAlbumResponse.class);
                        if (resGroup != null && ReqUtils.isSuccess(resGroup.getCode())) {
                            List<YNAlbum> data = resGroup.getData();
                            if (data.size() == 0)
                                return;
                            sendResidentNoticeType4(data);
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(MainActivity.this, CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        liteHttp.executeAsync(req);
    }

    private static final String ACTION_PEOPLESPACE_NOTICE1 = "com.yinian.action.peoplespace1";
    private static final String ACTION_PEOPLESPACE_NOTICE2 = "com.yinian.action.peoplespace2";
    private static final String ACTION_PEOPLESPACE_NOTICE3 = "com.yinian.action.peoplespace3";
    private static final String ACTION_PEOPLESPACE_NOTICE4 = "com.yinian.action.peoplespace4";
    private static final int NOTICE_ID_TYPE_0 = R.string.app_name;

    private void initRemoteViews1(RemoteViews remoteViews, List<YNAlbum> mDatas) {
        int days = getMiltime(mDatas.get(0).getMarkDate(), mDatas.get(0).getMarkRepeat());
        int diffWidth = DisplayUtils.getScreenWidthPixels(MainActivity.this) - DisplayUtils.dp2px(MainActivity.this, 75);
        float percent = (float) (days * 1.0 / 364);
        if (mDatas.get(0).getMarkRepeat().equals("1")) {
            remoteViews.setTextViewText(R.id.tv1, String.valueOf(days));
        } else {
            remoteViews.setTextViewText(R.id.tv1, String.valueOf(days) + "+");
        }
        if (days > 364) {
            remoteViews.setInt(R.id.iv1, "setBackgroundColor", Color.parseColor(mDatas.get(0).getMarkColor()));
            remoteViews.setTextViewText(R.id.tv1_tt, mDatas.get(0).getMarkContent());
        } else if (days + 32 >= 182 && days < 364) {
            remoteViews.setInt(R.id.tv1, "setBackgroundColor", Color.parseColor(mDatas.get(0).getMarkColor()));
            remoteViews.setInt(R.id.tv1, "setMinWidth", (int) (percent * diffWidth));
            remoteViews.setTextViewText(R.id.tv1_tt_short, mDatas.get(0).getMarkContent());
        } else {
            remoteViews.setInt(R.id.tv1, "setBackgroundColor", Color.parseColor(mDatas.get(0).getMarkColor()));
            if (mDatas.get(0).getMarkRepeat().equals("0")) {
                if (days < 55) {
                    remoteViews.setInt(R.id.tv1, "setMinWidth", UIHelper.dip2px(MainActivity.this, 42));
                } else {
                    remoteViews.setInt(R.id.tv1, "setMinWidth", (int) (percent * diffWidth));
                }
            } else {
                if (days < 40) {
                    remoteViews.setInt(R.id.tv1, "setMinWidth", UIHelper.dip2px(MainActivity.this, 32));
                } else {
                    remoteViews.setInt(R.id.tv1, "setMinWidth", (int) (percent * diffWidth));
                }
            }
            remoteViews.setTextViewText(R.id.tv1_tt_short, mDatas.get(0).getMarkContent());
        }

        Intent intent1 = new Intent(ACTION_PEOPLESPACE_NOTICE1);
        intent1.putExtra("ynalbum", mDatas.get(0));
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, (int) SystemClock.uptimeMillis(), intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.rl1, pendingIntent1);
    }

    private void initRemoteViews1clean(RemoteViews remoteViews) {
        remoteViews.setTextViewText(R.id.tv1, "");
        remoteViews.setInt(R.id.iv1, "setBackgroundColor", Color.parseColor("#00000000"));
        remoteViews.setTextViewText(R.id.tv1_tt, "");
        remoteViews.setInt(R.id.tv1, "setMinWidth", 0);
        remoteViews.setTextViewText(R.id.tv1_tt_short, "");
        remoteViews.setInt(R.id.tv1, "setBackgroundColor", Color.parseColor("#00000000"));
        Intent intent2 = new Intent("123");
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, (int) SystemClock.uptimeMillis(), intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.rl1, pendingIntent1);
    }

    private void initRemoteViewsclean(RemoteViews remoteViews) {
        initRemoteViews1clean(remoteViews);
        initRemoteViews2clean(remoteViews);
        initRemoteViews3clean(remoteViews);
        initRemoteViews4clean(remoteViews);
    }

    private void initRemoteViews2clean(RemoteViews remoteViews) {
        remoteViews.setTextViewText(R.id.tv2, "");
        remoteViews.setInt(R.id.iv2, "setBackgroundColor", Color.parseColor("#00000000"));
        remoteViews.setTextViewText(R.id.tv2_tt, "");
        remoteViews.setInt(R.id.tv2, "setMinWidth", 0);
        remoteViews.setTextViewText(R.id.tv2_tt_short, "");
        remoteViews.setInt(R.id.tv2, "setBackgroundColor", Color.parseColor("#00000000"));
        Intent intent2 = new Intent("123");
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, (int) SystemClock.uptimeMillis(), intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.rl2, pendingIntent1);
    }

    private void initRemoteViews3clean(RemoteViews remoteViews) {
        remoteViews.setTextViewText(R.id.tv3, "");
        remoteViews.setInt(R.id.iv3, "setBackgroundColor", Color.parseColor("#00000000"));
        remoteViews.setTextViewText(R.id.tv3_tt, "");
        remoteViews.setInt(R.id.tv3, "setMinWidth", 0);
        remoteViews.setTextViewText(R.id.tv3_tt_short, "");
        remoteViews.setInt(R.id.tv3, "setBackgroundColor", Color.parseColor("#00000000"));
        Intent intent2 = new Intent("123");
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, (int) SystemClock.uptimeMillis(), intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.rl3, pendingIntent1);
    }

    private void initRemoteViews4clean(RemoteViews remoteViews) {
        remoteViews.setTextViewText(R.id.tv4, "");
        remoteViews.setInt(R.id.iv4, "setBackgroundColor", Color.parseColor("#00000000"));
        remoteViews.setTextViewText(R.id.tv4_tt, "");
        remoteViews.setInt(R.id.tv4, "setMinWidth", 0);
        remoteViews.setTextViewText(R.id.tv4_tt_short, "");
        remoteViews.setInt(R.id.tv4, "setBackgroundColor", Color.parseColor("#00000000"));
        Intent intent2 = new Intent("123");
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, (int) SystemClock.uptimeMillis(), intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.rl4, pendingIntent1);
    }

    private void initRemoteViews2(RemoteViews remoteViews, List<YNAlbum> mDatas) {
        int days = getMiltime(mDatas.get(1).getMarkDate(), mDatas.get(1).getMarkRepeat());
        int diffWidth = DisplayUtils.getScreenWidthPixels(MainActivity.this) - DisplayUtils.dp2px(MainActivity.this, 75);
        float percent = (float) (days * 1.0 / 364);
        if (mDatas.get(1).getMarkRepeat().equals("1")) {
            remoteViews.setTextViewText(R.id.tv2, String.valueOf(days));
        } else {
            remoteViews.setTextViewText(R.id.tv2, String.valueOf(days) + "+");
        }
        if (days > 364) {
            remoteViews.setInt(R.id.iv2, "setBackgroundColor", Color.parseColor(mDatas.get(1).getMarkColor()));
            remoteViews.setTextViewText(R.id.tv2_tt, mDatas.get(1).getMarkContent());
        } else if (days + 32 >= 182 && days < 364) {
            remoteViews.setInt(R.id.tv2, "setBackgroundColor", Color.parseColor(mDatas.get(1).getMarkColor()));
            remoteViews.setInt(R.id.tv2, "setMinWidth", (int) (percent * diffWidth));
            remoteViews.setTextViewText(R.id.tv2_tt_short, mDatas.get(1).getMarkContent());
        } else {
            remoteViews.setInt(R.id.tv2, "setBackgroundColor", Color.parseColor(mDatas.get(1).getMarkColor()));
            if (mDatas.get(1).getMarkRepeat().equals("0")) {
                if (days < 55) {
                    remoteViews.setInt(R.id.tv2, "setMinWidth", UIHelper.dip2px(MainActivity.this, 42));
                } else {
                    remoteViews.setInt(R.id.tv2, "setMinWidth", (int) (percent * diffWidth));
                }
            } else {
                if (days < 40) {
                    remoteViews.setInt(R.id.tv2, "setMinWidth", UIHelper.dip2px(MainActivity.this, 32));
                } else {
                    remoteViews.setInt(R.id.tv2, "setMinWidth", (int) (percent * diffWidth));
                }
            }
            remoteViews.setTextViewText(R.id.tv2_tt_short, mDatas.get(1).getMarkContent());
        }
        Intent intent2 = new Intent(ACTION_PEOPLESPACE_NOTICE2);
        intent2.putExtra("ynalbum", mDatas.get(1));
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, (int) SystemClock.uptimeMillis(), intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.rl2, pendingIntent1);
    }

    private void initRemoteViews3(RemoteViews remoteViews, List<YNAlbum> mDatas) {
        int days = getMiltime(mDatas.get(2).getMarkDate(), mDatas.get(2).getMarkRepeat());
        int diffWidth = DisplayUtils.getScreenWidthPixels(MainActivity.this) - DisplayUtils.dp2px(MainActivity.this, 75);
        float percent = (float) (days * 1.0 / 364);
        if (mDatas.get(2).getMarkRepeat().equals("1")) {
            remoteViews.setTextViewText(R.id.tv3, String.valueOf(days));
        } else {
            remoteViews.setTextViewText(R.id.tv3, String.valueOf(days) + "+");
        }
        if (days > 364) {
            remoteViews.setInt(R.id.iv3, "setBackgroundColor", Color.parseColor(mDatas.get(2).getMarkColor()));
            remoteViews.setTextViewText(R.id.tv3_tt, mDatas.get(2).getMarkContent());
        } else if (days + 32 >= 182 && days < 364) {
            remoteViews.setInt(R.id.tv3, "setBackgroundColor", Color.parseColor(mDatas.get(2).getMarkColor()));
            remoteViews.setInt(R.id.tv3, "setMinWidth", (int) (percent * diffWidth));
            remoteViews.setTextViewText(R.id.tv3_tt_short, mDatas.get(2).getMarkContent());
        } else {
            remoteViews.setInt(R.id.tv3, "setBackgroundColor", Color.parseColor(mDatas.get(2).getMarkColor()));
            if (mDatas.get(2).getMarkRepeat().equals("0")) {
                if (days < 55) {
                    remoteViews.setInt(R.id.tv3, "setMinWidth", UIHelper.dip2px(MainActivity.this, 42));
                } else {
                    remoteViews.setInt(R.id.tv3, "setMinWidth", (int) (percent * diffWidth));
                }
            } else {
                if (days < 40) {
                    remoteViews.setInt(R.id.tv3, "setMinWidth", UIHelper.dip2px(MainActivity.this, 32));
                } else {
                    remoteViews.setInt(R.id.tv3, "setMinWidth", (int) (percent * diffWidth));
                }
            }
            remoteViews.setTextViewText(R.id.tv3_tt_short, mDatas.get(2).getMarkContent());
        }
        Intent intent2 = new Intent(ACTION_PEOPLESPACE_NOTICE3);
        intent2.putExtra("ynalbum", mDatas.get(2));
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, (int) SystemClock.uptimeMillis(), intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.rl3, pendingIntent1);
    }

    private void initRemoteViews4(RemoteViews remoteViews, List<YNAlbum> mDatas) {
        int days = getMiltime(mDatas.get(3).getMarkDate(), mDatas.get(3).getMarkRepeat());
        int diffWidth = DisplayUtils.getScreenWidthPixels(MainActivity.this) - DisplayUtils.dp2px(MainActivity.this, 75);
        float percent = (float) (days * 1.0 / 364);
        if (mDatas.get(3).getMarkRepeat().equals("1")) {
            remoteViews.setTextViewText(R.id.tv4, String.valueOf(days));
        } else {
            remoteViews.setTextViewText(R.id.tv4, String.valueOf(days) + "+");
        }
        if (days > 364) {
            remoteViews.setInt(R.id.iv4, "setBackgroundColor", Color.parseColor(mDatas.get(3).getMarkColor()));
            remoteViews.setTextViewText(R.id.tv4_tt, mDatas.get(3).getMarkContent());
        } else if (days + 32 >= 182 && days < 364) {
            remoteViews.setInt(R.id.tv4, "setBackgroundColor", Color.parseColor(mDatas.get(3).getMarkColor()));
            remoteViews.setInt(R.id.tv4, "setMinWidth", (int) (percent * diffWidth));
            remoteViews.setTextViewText(R.id.tv4_tt_short, mDatas.get(3).getMarkContent());
        } else {
            remoteViews.setInt(R.id.tv4, "setBackgroundColor", Color.parseColor(mDatas.get(3).getMarkColor()));
            if (mDatas.get(3).getMarkRepeat().equals("0")) {
                if (days < 55) {
                    remoteViews.setInt(R.id.tv4, "setMinWidth", UIHelper.dip2px(MainActivity.this, 42));
                } else {
                    remoteViews.setInt(R.id.tv4, "setMinWidth", (int) (percent * diffWidth));
                }
            } else {
                if (days < 40) {
                    remoteViews.setInt(R.id.tv4, "setMinWidth", UIHelper.dip2px(MainActivity.this, 32));
                } else {
                    remoteViews.setInt(R.id.tv4, "setMinWidth", (int) (percent * diffWidth));
                }
            }
            remoteViews.setTextViewText(R.id.tv4_tt_short, mDatas.get(3).getMarkContent());
        }
        Intent intent2 = new Intent(ACTION_PEOPLESPACE_NOTICE4);
        intent2.putExtra("ynalbum", mDatas.get(3));
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, (int) SystemClock.uptimeMillis(), intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.rl4, pendingIntent1);
    }

    @TargetApi(16)
    private void sendResidentNoticeType4(List<YNAlbum> mDatas) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
        builder.setOngoing(true);
        builder.setPriority(NotificationCompat.PRIORITY_MAX);
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.four_notification);
        int num = mDatas.size();
        if (num > 4) {
            num = 4;
        }
        switch (num) {
            case 1:
                initRemoteViewsclean(remoteViews);
                initRemoteViews1(remoteViews, mDatas);
                break;
            case 2:
                initRemoteViewsclean(remoteViews);
                initRemoteViews1(remoteViews, mDatas);
                initRemoteViews2(remoteViews, mDatas);
                break;
            case 3:
                initRemoteViewsclean(remoteViews);
                initRemoteViews1(remoteViews, mDatas);
                initRemoteViews2(remoteViews, mDatas);
                initRemoteViews3(remoteViews, mDatas);
                break;
            case 4:
                initRemoteViewsclean(remoteViews);
                initRemoteViews1(remoteViews, mDatas);
                initRemoteViews2(remoteViews, mDatas);
                initRemoteViews3(remoteViews, mDatas);
                initRemoteViews4(remoteViews, mDatas);
                break;
        }
        Intent intent = new Intent(MainActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        int requestCode = (int) SystemClock.uptimeMillis();
        PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        remoteViews.setOnClickPendingIntent(R.id.notice_view_type_0, pendingIntent);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setOngoing(true);
        Notification notification = builder.build();
        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
            notification.bigContentView = remoteViews;
            notification.flags |= Notification.FLAG_INSISTENT;
            notification.contentView = remoteViews;
            manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(NOTICE_ID_TYPE_0, notification);
        }
    }

    private int getMiltime(String time, String repeat) {
        //获取当前时间的毫秒值并根据重复判断得出天数
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long timeMil = 0;
        try {
            Date parse = simpleDateFormat.parse(time);
            timeMil = parse.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long currentTime = getCurrentTime();
        long diffMills = currentTime - timeMil;
        int days;
        if (repeat.equals("1") && diffMills > 0) {
//            int i = (int) (diffMills / 1000 / 3600 / 24) / 365;
//            int n = (int) (diffMills / 1000 / 3600 / 24) - 365 * i;
//            if (i>0){
//                days = n * (-1) + 365+1;
//            }else{
//                days = n * (-1) + 365;
//            }
            long currentMillis = System.currentTimeMillis();
            Date curDate = new Date(currentMillis);
            String time1 = simpleDateFormat.format(curDate);

            String[] split = time1.split("-");
            int yearInt = Integer.parseInt(split[0]) + 1;
            String[] split1 = time.split("-");
            time = String.valueOf(yearInt) + "-" + split1[1] + "-" + split1[2];
//            Log.d("yuhao", "time="+time);
            try {
                Date parse = simpleDateFormat.parse(time);
                timeMil = parse.getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            diffMills = currentTime - timeMil;
        }
        diffMills = Math.abs(diffMills);
        days = (int) (diffMills / 1000 / 3600 / 24);
        return days;
    }

    private Long getCurrentTime() {
        long currentMillis = System.currentTimeMillis();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(currentMillis);
        String time = formatter.format(curDate);
        long timeMil = 0;
        try {
            Date parse = formatter.parse(time);
            timeMil = parse.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeMil;
    }

    private static final String DIR = StorageUtil.getSDPath();
    private RecorderAndPlayUtil mRecorderUtil = null;

    private void InitRecorder() {
        mRecorderUtil = new RecorderAndPlayUtil(DIR);
        mRecorderUtil.getRecorder().setHandle(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MP3Recorder.MSG_ERROR_GET_MIN_BUFFERSIZE:
                    case MP3Recorder.MSG_ERROR_CREATE_FILE:
                    case MP3Recorder.MSG_ERROR_REC_START:
                    case MP3Recorder.MSG_ERROR_AUDIO_RECORD:
                    case MP3Recorder.MSG_ERROR_AUDIO_ENCODE:
                    case MP3Recorder.MSG_ERROR_WRITE_FILE:
                    case MP3Recorder.MSG_ERROR_CLOSE_FILE:
                    case MP3Recorder.MSG_ERROR_AUDIO_LENGHT_NULL:
                        mRecorderUtil.stopRecording();
                        break;
                }
            }
        });
        mRecorderUtil.startRecording();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRecorderUtil.stopRecording();
            }
        }, 100);
        String rpath = mRecorderUtil.getRecorderPath();
        if (!StringUtils.isEmpty(rpath)) {
            File f = new File(rpath);
            if (f.exists())
                f.delete();
        }
    }

    private void checkUpdataAPP() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        StringRequest req = new StringRequest(getString(R.string.CHECK_VERSION_UPDATE))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            JSONObject updatejson = new JSONObject(s.toString());
                            if (updatejson.optInt("code") == 0) {
                                String versionNo = updatejson.optJSONArray("data").optJSONObject(0).optString("versionNo");
                                String versionUrl = updatejson.optJSONArray("data").optJSONObject(0).optString("versionUrl");
                                UpdateManager updateManager = new UpdateManager(versionNo, versionUrl, "检测到有新的版本，请下载更新！", MainActivity.this);
                                updateManager.checkUpdate();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(MainActivity.this, CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        liteHttp.executeAsync(req);
    }

    private android.app.AlertDialog.Builder conflictBuilder;
    private android.app.AlertDialog.Builder accountRemovedBuilder;
    private boolean isConflictDialogShow;
    private boolean isAccountRemovedDialogShow;

    /**
     * show the dialog when user logged into another device
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        DemoHelper.getInstance().logout(false, null);
        ExitYiNian();
        String st = getResources().getString(R.string.Logoff_notification);
        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (conflictBuilder == null)
                    conflictBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
                conflictBuilder.setTitle(st);
                conflictBuilder.setMessage(R.string.connect_conflict);
                conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        conflictBuilder = null;
                        finish();
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
                conflictBuilder.setCancelable(false);
                conflictBuilder.create().show();
                isConflict = true;
            } catch (Exception e) {
                EMLog.e(TAG, "---------color conflictBuilder error" + e.getMessage());
            }
        }
    }

    /**
     * show the dialog if user account is removed
     */
    private void showAccountRemovedDialog() {
        isAccountRemovedDialogShow = true;
        DemoHelper.getInstance().logout(false, null);
        ExitYiNian();
        String st5 = getResources().getString(R.string.Remove_the_notification);
        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (accountRemovedBuilder == null)
                    accountRemovedBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
                accountRemovedBuilder.setTitle(st5);
                accountRemovedBuilder.setMessage(R.string.em_user_remove);
                accountRemovedBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        accountRemovedBuilder = null;
                        finish();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    }
                });
                accountRemovedBuilder.setCancelable(false);
                accountRemovedBuilder.create().show();
            } catch (Exception e) {
                EMLog.e(TAG, "---------color userRemovedBuilder error" + e.getMessage());
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) {
            showConflictDialog();
        } else if (intent.getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
            showAccountRemovedDialog();
        }
    }

    @TargetApi(23)
    private void requestPermissions() {
        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
            @Override
            public void onGranted() {
//				Toast.makeText(MainActivity.this, "All permissions have been granted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDenied(String permission) {
                //Toast.makeText(MainActivity.this, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initjudieAccountRemove() {
        if (getIntent().getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) {
            showConflictDialog();
        } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
            showAccountRemovedDialog();
        }
    }

    private void initContinueUpLoadService() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 若有未上传图片，后台自动上传
                Intent intent = new Intent(MainActivity.this, UpLoadService.class);
                intent.setAction(ACTIONs.actionStartUp);
                startService(intent);
            }
        }, 300);
    }

    // 上传CID
    private void updateCID(final boolean isEnter) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                postCID(isEnter);
            }
        }, 3000);
    }

    public void postCID(boolean isEnter) {
        String type = isEnter ? CommonConstants.YNS_TYPE_ENTER : CommonConstants.YNS_TYPE_QUIT;
        String cid = isEnter ? PushManager.getInstance().getClientid(this) : "";
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_CID, cid);
        mParam.put(CommonConstants.YNS_INFO_TYPE, type);
        mParam.put(CommonConstants.YNS_DEVICE, CommonConstants.YNS_DEVICE_ANDROID);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynUpdateCid))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resCid = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resCid.getCode())) {
                        } else {
                            updateCID(true);
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        updateCID(true);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private long mLastBackTime = 0;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - mLastBackTime > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mLastBackTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
//            System.exit(0);
//            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    private void initView() {
        if (YNSingleton.getInstance().getScreenWidth() == 0)
            YNSingleton.getInstance().setScreenWidth(this);
        mViewPager = (NoScrollViewPager) findViewById(R.id.vp_main_viewpager);
        mViewPager.setScrollble(true);
        tabiv1 = (RelativeLayout) findViewById(R.id.btn_space_selector);
        tabiv2 = (ImageView) findViewById(R.id.btn_middle_selector);
        my_album_num = (TextView) findViewById(R.id.my_album_num);
        btn_middle_selector_copy = (ImageView) findViewById(R.id.btn_middle_selector_copy);
        tabiv3 = (RelativeLayout) findViewById(R.id.btn_me_selector);
        select1 = (ImageView) findViewById(R.id.iv_space_selector);
        selecttv1 = (TextView) findViewById(R.id.tv_space_selector);
        select3 = (ImageView) findViewById(R.id.iv_me_selector);
        selecttv3 = (TextView) findViewById(R.id.tv_me_selector);
        buttons_cover_day = (TextView) findViewById(R.id.buttons_cover_day);
        buttons_cover_week = (TextView) findViewById(R.id.buttons_cover_week);
        buttons_cover_yeanmoutn = (TextView) findViewById(R.id.buttons_cover_yeanmoutn);
        buttons_cover_day.setText(TimeUtils.getNowDay());
        buttons_cover_week.setText(TimeUtils.getNowWeek());
        buttons_cover_yeanmoutn.setText(TimeUtils.getNowYearMouth());
        tabiv1.setOnClickListener(this);
        tabiv2.setOnClickListener(this);
        btn_middle_selector_copy.setOnClickListener(this);
        tabiv3.setOnClickListener(this);
        ll_buttons = (RelativeLayout) findViewById(R.id.ll_buttons);
        ll_buttons_ll = (RelativeLayout) findViewById(R.id.ll_buttons_ll);
        buttons_cover = (ImageView) findViewById(R.id.buttons_cover);
        buttons_cover.setClickable(true);
        buttons_cover.setOnClickListener(this);
        buttons_cover_top = (LinearLayout) findViewById(R.id.buttons_cover_top);
        findViewById(R.id.tv_image).setOnClickListener(this);
        findViewById(R.id.tv_video).setOnClickListener(this);
        findViewById(R.id.tv_word).setOnClickListener(this);
        findViewById(R.id.tv_mic).setOnClickListener(this);
        findViewById(R.id.tv_location).setOnClickListener(this);
        findViewById(R.id.tv_pailide).setOnClickListener(this);
        rl_timeline_guide = (RelativeLayout) findViewById(R.id.rl_timeline_guide);
        anim_pailide_new = (ImageView) findViewById(R.id.anim_pailide_new);
//        anim_pailide_new.setImageResource(R.drawable.anim_pailide_new);
//        anim_pailide_new_animaition = (AnimationDrawable) anim_pailide_new.getDrawable();
//        anim_pailide_new.post(new Runnable() {
//            @Override
//            public void run() {
//                anim_pailide_new_animaition.start();
//            }
//        });
        rl_album_newuser = (RelativeLayout) findViewById(R.id.rl_album_newuser);
        rl_album_newuser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rl_album_newuser.setVisibility(View.GONE);
            }
        });
        fragments.add(new HomeAlbumFragment());
        fragments.add(new PeopleTimeLineFragment());
        fragments.add(new MineFragement());
        mViewPagerAdaper = new MainFragmentAdapter(getSupportFragmentManager(), fragments);
        mViewPager.setAdapter(mViewPagerAdaper);
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        if (!gisswitch) {
                            tabiv2.setImageResource(R.drawable.anim_btns_left);
                            _animaition = (AnimationDrawable) tabiv2.getDrawable();
                            _animaition.start();
                        }
                        select1.setImageResource(R.drawable.icon_space_after);
                        selecttv1.setTextColor(Color.parseColor("#333333"));
                        select3.setImageResource(R.drawable.icon_my_before);
                        selecttv3.setTextColor(Color.parseColor("#999999"));
                        gisswitch = true;
                        Glide.get(MainActivity.this).clearMemory();
                        System.gc();
                        break;
                    case 1:
                        if (gisswitch) {
                            tabiv2.setImageResource(R.drawable.anim_btns_right);
                            _animaition2 = (AnimationDrawable) tabiv2.getDrawable();
                            _animaition2.start();
                        }
                        select1.setImageResource(R.drawable.icon_space_before);
                        selecttv1.setTextColor(Color.parseColor("#999999"));
                        selecttv3.setTextColor(Color.parseColor("#999999"));
                        select3.setImageResource(R.drawable.icon_my_before);
                        gisswitch = false;
                        break;
                    case 2:
                        if (!gisswitch) {
                            tabiv2.setImageResource(R.drawable.anim_btns_left);
                            _animaition = (AnimationDrawable) tabiv2.getDrawable();
                            _animaition.start();
                        }
                        select1.setImageResource(R.drawable.icon_space_before);
                        selecttv1.setTextColor(Color.parseColor("#999999"));
                        select3.setImageResource(R.drawable.icon_my_after);
                        selecttv3.setTextColor(Color.parseColor("#333333"));
                        gisswitch = true;
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        mViewPager.setCurrentItem(1);
        // 获取个人数据
        Intent mIntent = new Intent(this, AlbumService.class);
        mIntent.setAction(ACTIONs.actionGetUser);
        startService(mIntent);
        if (application.getCurID() <= 0) {
            intent2Activity(SplashActivity2.class);
        }
        rl_timeline_guide = (RelativeLayout) findViewById(R.id.rl_timeline_guide);
//        rl_timeline_guide.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                rl_timeline_guide.setVisibility(View.GONE);
//                SpUtils.put(MainActivity.this, "homeZhidaole", true);
//            }
//        });
//        JudgeIsNewUser();
        getUserData();
        boolean homeZhidaole = SpUtils.getBoolean(MainActivity.this, "homeZhidaole");
        if (!homeZhidaole) {
            rl_timeline_guide.setVisibility(View.VISIBLE);
        } else {
            rl_timeline_guide.setVisibility(View.GONE);
        }
    }

    private void getUserData() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.GetUserData))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNGetUserResponse resUser = gson.fromJson(s, YNGetUserResponse.class);
                        if (resUser != null && ReqUtils.isSuccess(resUser.getCode()) && resUser.getData().size() > 0) {
                            // 通知动态更新
                            String Event = resUser.getData().get(0).getEvent();
                            if (Integer.parseInt(Event) != 0) {
                                eventnum = Integer.parseInt(Event) + 1;
                                my_album_num.setText(eventnum + "");
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private int eventnum = 1;

//    private void JudgeIsNewUser() {
//        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
//        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
//        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynJudgeUserIsNew))
//                .setMethod(HttpMethods.Post)
//                .setParamMap(mParam)
//                .setHttpListener(new HttpListener<String>(true, false, true) {
//                    @Override
//                    public void onSuccess(String s, Response<String> response) {
//                        YNCommonResponse isNewUser = gson.fromJson(s, YNCommonResponse.class);
//                        if (isNewUser != null && ReqUtils.isNewUser(isNewUser.getCode())) {
//                            rl_album_newuser.setVisibility(View.GONE);
//                        } else {
//                            rl_album_newuser.setVisibility(View.VISIBLE);
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
//                    }
//                });
//        liteHttp.executeAsync(req);
//    }

//    public void initPuzzleGameDialog() {
//        SharedPreferences sp = getSharedPreferences("puzzle_date", MODE_PRIVATE);
//        SharedPreferences.Editor editor = sp.edit();
//        Time time = new Time("GMT+8");
//        time.setToNow();
//        String date = String.valueOf(time.year) + String.valueOf(time.month + 1) + String.valueOf(time.monthDay);
//        if (!sp.getString("date", "").equals(date)) {
//            intent2Activity(PuzzleGameDialogActivity.class);
//        }
//        editor.putString("date", date);
//        editor.commit();
//    }

    // 分析并执行动作
    BroadcastReceiver mUserBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case "mViewPagerOne":
                    try {
                        Field field = mViewPager.getClass().getField("mCurItem");
                        field.setAccessible(true);
                        field.setInt(mViewPager, 1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mViewPagerAdaper.notifyDataSetChanged();
                    mViewPager.setCurrentItem(1);
                    mViewPager.setTranslationX(0);
                    mViewPager.setScrollble(true);
                    break;
                case ACTIONs.spacetopsgone:
                    buttons_cover.setVisibility(View.GONE);
                    buttons_cover_top.setVisibility(View.GONE);
                    break;
                case ACTIONs.actionToPeopleTimeLine:
                    mViewPager.setCurrentItem(1);
                    break;
                // 通知显示今日忆
                case ACTIONs.actionDoPopToday:
                    if (DisplayUtils.isForeground(MainActivity.this, MainActivity.class.getName())) {
                        intent2Activity(TodayShowActivity.class);
                    }
                    break;
                //通知显示每日推送
                case ACTIONs.actionDoPopEveryDayNotice:
                    if (DisplayUtils.isForeground(MainActivity.this, MainActivity.class.getName())) {
                        intent2Activity(EveryDayNoticeDialogActivity.class);
                    }
                    break;
                case ACTIONs.Exit:
                    if (manager != null)
                        manager.cancel(NOTICE_ID_TYPE_0);
                    finish();
//                    System.exit(0);
                    break;
                case ACTIONs.record:
                    num++;
                    String key = intent.getStringExtra("key");
                    int value = intent.getIntExtra("value", 0);
                    String[] split = key.split("_");
                    if (split[1].equals("3")) {
                        if (map3.containsKey(split[0])) {
                            int aDouble = map3.get(split[0]);
                            aDouble = aDouble + value;
                            map3.put(split[0], aDouble);
                        } else {
                            map3.put(split[0], value);
                        }
                    }
                    if (split[1].equals("4")) {
                        if (map4.containsKey(split[0])) {
                            int aDouble = map4.get(split[0]);
                            aDouble = aDouble + value;
                            map4.put(split[0], aDouble);
                        } else {
                            map4.put(split[0], value);
                        }
                    }
                    if (split[1].equals("5")) {
                        if (map5.containsKey(split[0])) {
                            int aDouble = map5.get(split[0]);
                            aDouble = aDouble + value;
                            map5.put(split[0], aDouble);
                        } else {
                            map5.put(split[0], value);
                        }
                    }
                    if (split[1].equals("6")) {
                        if (map6.containsKey(split[0])) {
                            int aDouble = map6.get(split[0]);
                            aDouble = aDouble + value;
                            map6.put(split[0], aDouble);
                        } else {
                            map6.put(split[0], value);
                        }
                    }
                    if (num == 30) {
                        //启动服务上传记录的埋点数据
                        num = 0;
//                        Log.d("yuhao", "num30");
                        toJson(true);
                    }
                    break;
                case ACTIONs.network:
                    if (netType.size() >= 2) {
                        netType.clear();
                    }
                    ConnectivityManager connectivityManager = (ConnectivityManager)
                            getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                    if (networkInfo == null) {
                        netType.add(-1);
                    } else {
                        netType.add(networkInfo.getType());
                    }
                    if (netType.size() == 2 && netType.get(0) < 0 && netType.get(1) >= 0) {
                        updateCID(true);
//                        uploadFrisGiftPacket();
                        noticeServiceInit();
                        //将上次存储的数据上传服务器
                        String json = SpUtils.getString(MainActivity.this, "json");
                        if (json.startsWith("{")) {
                            Intent intent1 = new Intent(MainActivity.this, StatisticsService.class);
                            intent1.setAction(ACTIONs.uploadRecode);
                            intent1.putExtra("json", json);
                            startService(intent1);
                        }
                        Intent mIntent = new Intent(MainActivity.this, AlbumService.class);
                        mIntent.setAction(ACTIONs.actionGetUser);
                        startService(mIntent);
                    }
                    break;
                case "mainerweima":
                    startActivityForResult(new Intent(MainActivity.this,
                            CaptureActivity.class), SCANER_CODE);
                    break;
                case "ptlftakephoto":
                    ImageUtils.pickImageFromCamera(MainActivity.this);
                    break;
                case "ptlfpickphoto":
                    ImageUtils.pickImageFromAlbum(MainActivity.this);
                    break;
                case "OpenButtons":
                    OpenButtons();
                    break;
                case "VpIsScroll":
                    boolean VpIsScroll = intent.getBooleanExtra("VpIsScroll", false);
                    mViewPager.setScrollble(VpIsScroll);
                    break;
            }
        }
    };

    // 通知后台加载数据
    private void noticeServiceInit() {
        Intent mIntent = new Intent(this, AlbumService.class);
        mIntent.setAction(ACTIONs.actionGetAlbum);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID());
        startService(mIntent);
    }

    private void toJson(boolean isUpLoad) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        Iterator<Map.Entry<String, Integer>> it3 = map3.entrySet().iterator();
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        try {
            while (it3.hasNext()) {
                Map.Entry<String, Integer> next3 = it3.next();
                String key = next3.getKey();
                int value = next3.getValue();
                jsonObject1.put(key, value);
                jsonObject2.put("data", jsonObject1);
                jsonObject2.put("type", 3);
            }
            if (!jsonObject2.isNull("data")) {
                jsonArray.put(jsonObject2);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Iterator<Map.Entry<String, Integer>> it4 = map4.entrySet().iterator();
        JSONObject jsonObject3 = new JSONObject();
        JSONObject jsonObject4 = new JSONObject();
        try {
            while (it4.hasNext()) {
                Map.Entry<String, Integer> next4 = it4.next();
                String key = next4.getKey();
                int value = next4.getValue();
                jsonObject3.put(key, value);
                jsonObject4.put("data", jsonObject3);
                jsonObject4.put("type", 4);
            }
            if (!jsonObject4.isNull("data")) {
                jsonArray.put(jsonObject4);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Iterator<Map.Entry<String, Integer>> it5 = map5.entrySet().iterator();
        JSONObject jsonObject5 = new JSONObject();
        JSONObject jsonObject6 = new JSONObject();
        try {
            while (it5.hasNext()) {
                Map.Entry<String, Integer> next5 = it5.next();
                String key = next5.getKey();
                int value = next5.getValue();
                jsonObject5.put(key, value);
                jsonObject6.put("data", jsonObject5);
                jsonObject6.put("type", 5);
            }
            if (!jsonObject6.isNull("data")) {
                jsonArray.put(jsonObject6);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Iterator<Map.Entry<String, Integer>> it6 = map6.entrySet().iterator();
        JSONObject jsonObject7 = new JSONObject();
        JSONObject jsonObject8 = new JSONObject();
        try {
            while (it6.hasNext()) {
                Map.Entry<String, Integer> next6 = it6.next();
                String key = next6.getKey();
                int value = next6.getValue();
                jsonObject7.put(key, value);
                jsonObject8.put("data", jsonObject7);
                jsonObject8.put("type", 6);
            }
            if (!jsonObject8.isNull("data")) {
                jsonArray.put(jsonObject8);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            jsonObject.put("userid", application.getCurID());
            jsonObject.put("version", DisplayUtils.getVersion(MainActivity.this));
            jsonObject.put("device", "Android");
            jsonObject.put("totalData", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Log.d("yuhao", "toJson=" + jsonObject.toString());
        if (isUpLoad) {
            //记满30次上传服务器
            Intent intent = new Intent(MainActivity.this, StatisticsService.class);
            intent.setAction(ACTIONs.uploadRecode);
            intent.putExtra("json", jsonObject.toString());
            startService(intent);
            map3.clear();
            map4.clear();
            map5.clear();
            map6.clear();
        } else {
            //不满30次时将数据转成json存储起来，下次进入应用直接上传
            SpUtils.put(MainActivity.this, "json", jsonObject.toString());
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionMymessageNums);
        myIntentFilter.addAction(ACTIONs.actionDoPopToday);
        myIntentFilter.addAction(ACTIONs.actionDoPopEveryDayNotice);
        myIntentFilter.addAction(ACTIONs.Exit);
        myIntentFilter.addAction(ACTIONs.record);
        myIntentFilter.addAction(ACTIONs.network);
        myIntentFilter.addAction("mainerweima");
        myIntentFilter.addAction("ptlftakephoto");
        myIntentFilter.addAction("ptlfpickphoto");
        myIntentFilter.addAction(ACTIONs.actionToPeopleTimeLine);
        myIntentFilter.addAction(ACTIONs.spacebuttonsgone);
        myIntentFilter.addAction(ACTIONs.spacetopsgone);
        myIntentFilter.addAction("mViewPagerOne");
        myIntentFilter.addAction("OpenButtons");
        myIntentFilter.addAction("VpIsScroll");
        registerReceiver(mUserBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ImageUtils.REQUEST_CODE_FROM_ALBUM:
                if (resultCode == RESULT_CANCELED) {
                    return;
                }
                Uri imageUri = data.getData();
                beginCrop(imageUri);
                break;
            case ImageUtils.REQUEST_CODE_FROM_CAMERA:
                if (resultCode == RESULT_CANCELED) {
                    ImageUtils.deleteImageUri(this, ImageUtils.imageUriFromCamera);
                } else {
                    Uri imageUriCamera = ImageUtils.imageUriFromCamera;
                    beginCrop(imageUriCamera);
                }
                break;
            case Crop.REQUEST_CROP:
                handleCrop(resultCode, data);
                break;
            case SCANER_CODE:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String scanResult = bundle.getString("codedContent");
                    Log.i("xjs", "scanResult===>" + scanResult);
                    if (!StringUtils.isEmpty(scanResult)) {
                        if (scanResult.contains("http")) {
                            if (scanResult.contains("sharewx")) {
                                ToJoinZone(scanResult);
                            } else {
                                startActivity(new Intent(MainActivity.this, TimeGoodsWebActivity.class).putExtra("url", scanResult));
                            }
                        }
                    }
                }
                break;
        }
    }

    private String bgUrl;

    // 处理图像剪切结果
    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            bgUrl = ImageUtils.getImageAbsolutePath19(this, Crop.getOutput(result));
            sendBroadcast(new Intent("updatebgImg").putExtra("img", bgUrl));
            getCropToken();
        } else if (resultCode == Crop.RESULT_ERROR) {
            showToast("处理图片失败");
        }
    }

    private void beginCrop(Uri source) {
        File cropFile = new File(mTempDir, "Temp_" + String.valueOf(System.currentTimeMillis()) + ".png");
        Uri outputUri = Uri.fromFile(cropFile);
        new Crop(source).output(outputUri).setCropType(false).start(this);
    }

    private void getCropToken() {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            application.setUpToken(resToken.getData().get(0).getToken());
                            getAvatarAddress();
                        } else {
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void getAvatarAddress() {
        String prefix = bgUrl.substring(bgUrl.lastIndexOf(".") + 1);
        final String imgName = UUID.randomUUID().toString() + "." + prefix;
        mUpManager.put(bgUrl, imgName, application.getUpToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        doBgPost(key, imgName);
                    }
                }, new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            public void progress(String key, double percent) {
                            }
                        }, null));
    }

    // 修改相册背景
    private void doBgPost(String key, final String iName) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_IDD, String.valueOf(YNSingleton.getInstance().getCurAlbum().getGroupid()));
        mParam.put(CommonConstants.YNS_URL, key);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynModifyGroupPic))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resAlertBg = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resAlertBg.getCode())) {
                            YNSingleton.getInstance().getCurAlbum().setGpic(CommonConstants.YNQNURL + iName);
                            Intent mIntent = new Intent(ACTIONs.actionAlertGPic);
                            sendBroadcast(mIntent);
                            showToast("修改成功");
                        } else {
                            showToast("修改失败");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void ToJoinZone(String scanResult) {
        try {
            String code = scanResult.substring(scanResult.lastIndexOf("code") + 5, scanResult.length());
            String inviteInfo = YNInviteSecret.decryptDES(code, getString(R.string.UNKNOW_ID));
            final String groupId = inviteInfo.substring(inviteInfo.lastIndexOf("=") + 1, inviteInfo.length());
            LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
            mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
            mParam.put(CommonConstants.YNS_GROUP_ID, groupId);
            StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynEnterAlbum))
                    .setMethod(HttpMethods.Post)
                    .setParamMap(mParam)
                    .setHttpListener(new HttpListener<String>(true, false, true) {
                        @Override
                        public void onSuccess(String s, Response<String> response) {
                            Log.i("xjs", "scanResult+sss===>" + s);
                            try {
                                JSONObject jsonObject = new JSONObject(s);
                                if (jsonObject.optInt("code") == 0) {
                                    getOfficialInfo(groupId);
                                    Intent statintentbtnjoin = new Intent(ACTIONs.record);
                                    statintentbtnjoin.putExtra("key", "二维码_4");
                                    statintentbtnjoin.putExtra("value", 1);
                                    sendBroadcast(statintentbtnjoin);
                                } else if (jsonObject.optInt("code") == 1010) {
                                    Toast.makeText(MainActivity.this, "已加入该圈子", Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(HttpException e, Response<String> response) {
                            showToast(CommonConstants.YN_NET_LINK);
                        }
                    });
            liteHttp.executeAsync(req);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getOfficialInfo(final String ids) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_ID, ids);
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowSingleOfficialAlbum))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
//                        Log.i("xjs", "main+getOfficialInfo===>");
                        YNAlbumResponse resOfficialGroup = gson.fromJson(s, YNAlbumResponse.class);
                        if (resOfficialGroup != null && ReqUtils.isSuccess(resOfficialGroup.getCode())) {
                            YNAlbum tarAlbum = resOfficialGroup.getData().get(0);
                            YNSingleton.getInstance().setCurAlbum(tarAlbum);
                            application.setCurGid(Integer.parseInt(ids));
                            sendBroadcast(new Intent(ACTIONs.actionUpdateFristAlbum).putExtra("update", true));
                            sendBroadcast(new Intent(ACTIONs.actionToPeopleTimeLine));
                            sendBroadcast(new Intent(ACTIONs.actionAlbumInit));
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    public void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
        toJson(false);
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        Intent intent = new Intent(ACTIONs.record);
        intent.putExtra("key", "homepage_3");
        intent.putExtra("value", new Long(System.currentTimeMillis() - fristTime).intValue());
        sendBroadcast(intent);
    }

    private long fristTime;

    public void onResume() {
        super.onResume();
        sendBroadcast(new Intent(ACTIONs.actionMymessageNums));
        PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        fristTime = System.currentTimeMillis();
    }

    @Override
    protected void onDestroy() {
        long difTime = System.currentTimeMillis() - time;
        if (difTime < 0) {
            difTime = -difTime;
        }
        SpUtils.put(MainActivity.this, "time", difTime);
        unregisterReceiver(mUserBroadcastReceiver);
        super.onDestroy();
        SharedPreferences sp = getSharedPreferences("OURINFO", MODE_PRIVATE);
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean("active", false);
        ed.commit();
    }

}

